/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.dx.financehy.modules.security.service;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.dx.financehy.exception.BadRequestException;
import com.dx.financehy.exception.EntityNotFoundException;
import com.dx.financehy.modules.security.config.bean.LoginProperties;
import com.dx.financehy.modules.security.domain.dto.JwtUserDto;
import com.dx.financehy.modules.security.utils.LoginUtil;
import com.dx.financehy.modules.system.domain.User;
import com.dx.financehy.modules.system.domain.dto.UserDto;
import com.dx.financehy.modules.system.domain.dto.UserLoginDto;
import com.dx.financehy.modules.system.mapper.UserMapper;
import com.dx.financehy.utils.ConvertUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author Zheng Jie
 * @date 2018-11-22
 */
@RequiredArgsConstructor
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
//    private final UserService userService;
    private final LoginProperties loginProperties;
    private final LoginUtil loginUtil;
    private final UserMapper userMapper;
    private final UserCacheManager userCacheManager;

    public void setEnableCache(boolean enableCache) {
        this.loginProperties.setCacheEnable(enableCache);
    }

    @Override
    @DS("operate")
    public JwtUserDto loadUserByUsername(String username) {
        JwtUserDto jwtUserDto = null;
        if (loginProperties.isCacheEnable()) { // 开启缓存
            jwtUserDto = userCacheManager.getUserCache(username);
        }
        if (jwtUserDto == null) {
            UserLoginDto user = null;
            String phone = username.split(":")[0];
            try {
                UserDto userDto = userMapper.queryLoginUser(phone);
                if (userDto == null) {
                    throw new EntityNotFoundException(User.class, "name", phone);
                }
                if (userDto.getIsLogin() == false){
                    loginUtil.incrementCount(username);
                    throw new BadRequestException("账号不允许登录");
                }

                user = ConvertUtil.convert(userDto, UserLoginDto.class);
            } catch (EntityNotFoundException e) {
                loginUtil.incrementCount(username);
                throw new UsernameNotFoundException("用户名或密码错误", e);
            }
            if (user == null) {
                loginUtil.incrementCount(username);
                throw new UsernameNotFoundException("用户名或密码错误");
            } else {
                if (!user.getEnabled()) {
                    throw new BadRequestException("账号未激活！");
                }
                jwtUserDto = new JwtUserDto(
                        user,
                        null
                );
                // 添加缓存数据
                userCacheManager.addUserCache(username, jwtUserDto);
            }
        }
        return jwtUserDto;
    }
}
